package com.example.aloy.fragment

import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.example.aloy.BasicBundleData


// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val BUNDLE_DATA = "bundle_data"


abstract class BasicFragment(bundleData: BasicBundleData? = null) : Fragment() {

    private var bundleData: BasicBundleData? = null

    private var _binding: ViewBinding? = null
    val binding get() = _binding!!

    private var primaryColorInt: Int? = null

    interface OnPrimaryColorListener {
        fun onPrimaryColorChanged(@ColorInt primaryColorInt: Int)
    }

    private var primaryColorListener: OnPrimaryColorListener? = null

    init {
        arguments = Bundle().apply {
            putSerializable(BUNDLE_DATA, bundleData)
        }
    }

    // API 33以上
    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            bundleData = it.getSerializable(BUNDLE_DATA, BasicBundleData::class.java)
        }
    }

    abstract fun onBindingView(): ViewBinding

    // 是否拦截事件
    open fun isInterceptEvent(): Boolean = false

    fun setPrimaryColorRes(@ColorRes colorRes: Int) {
        context?.let {
            setPrimaryColorInt(ContextCompat.getColor(it, colorRes))
        }
    }

    fun setPrimaryColorInt(@ColorInt colorInt: Int) {
        primaryColorInt = colorInt
        primaryColorListener?.onPrimaryColorChanged(colorInt)
    }

    fun setPrimaryColorListener(listener: OnPrimaryColorListener?) {
        primaryColorListener = listener
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = onBindingView()
        return binding.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}